package djrain.lilochat.client;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.google.android.maps.GeoPoint;

import djrain.lib.ToastEx;

public class LiloMessage extends Handler
{
	private static final String tag = "LiloMessage";
	private Lilo lilo;

	public LiloMessage(Lilo lilo)
	{
		this.lilo = lilo;
	}

	private StringBuffer receiveString = new StringBuffer(1024);

	private synchronized void onReceive(String message)
	{
//		receiveString.append(message);
//		while (parserMessage())
//			message(getMessage());
		
		lilo.setReceiveMessage(message+"\n");
	}

	// Message 를 파싱하여 몇게의 메시지가 있는지 알려 준다.
	private boolean parserMessage()
	{
		return false;
	}

	public synchronized String getMessage()
	{
		// TODO Message 중에서 첫번째 Message를 리턴한다.
		Log.e("getReceiveString0", receiveString.toString());
		String sub = receiveString.substring(0, receiveString.length());
		Log.e("getReceiveString1", receiveString.toString());
		return sub;
	}

	// 완전한 하나의 Message
	public void message(String str)
	{
		if (isCommand(str))
			processCommand(str);
		else
			processChat(str);
	}

	public static void sendMessage(Handler handler, String string)
	{
		Message msg = handler.obtainMessage();
		msg.what = 1;
		Bundle b = new Bundle();
		b.putString("chat", string);
		msg.setData(b);
		handler.sendMessage(msg);
	}

	private void processChat(String message)
	{
		lilo.updateYouChat(message);
	}

	@Override
	public void handleMessage(Message msg)
	{
		if (msg.what == 1)
		{
			Bundle b = msg.getData();
			String message = b.getString("chat");
			onReceive(message);
		}

		super.handleMessage(msg);
	}

	public boolean isCommand(String str)
	{
		return str.substring(0, 1).equals("/");
	}

	public void processCommand(String command)
	{
		if (command.substring(0, 5).equalsIgnoreCase("/@   "))
		{// TODO 위치 업데이트

			String geoPointString = command.substring(5).trim();
			GeoPoint geoPoint = null;
			lilo.updateYouLocation(geoPoint);
		}
		else if (command.substring(0, 5).equalsIgnoreCase("/al  "))
		{ // TODO 이름바꾸기
			String newname = command.substring(5).trim();
		}
		else if (command.substring(0, 5).equalsIgnoreCase("/note"))
		{ // change user name
			String note = command.substring(5).trim();
			// TODO 공지
		}
		else
		{
			Log.e("Lilo", "!Unknown Command:" + ">" + command + "<");
		}
	}
}
